//
//  NSString+SHA256.m
//  IAPManager
//
//  Created by 唐可雄 on 2019/3/6.
//  Copyright © 2019年 swustyc. All rights reserved.
//

#import "NSString+SHA256.h"

#import <CommonCrypto/CommonCrypto.h>

@implementation NSString (SHA256)

- (NSString *)hashedValue {
    const int HASH_SIZE = 32;
    unsigned char hashedChars[HASH_SIZE];
    const char *chars = [self UTF8String];
    size_t len = strlen(chars);
    
    if (len > UINT32_MAX) {
        NSLog(@"Account name too long to hash: %@", self);
        return nil;
    }
    
    CC_SHA256(chars, (CC_LONG)len, hashedChars);
    
    NSMutableString *result = [[NSMutableString alloc] init];
    for (int i = 0; i < HASH_SIZE; i++) {
        if (i != 0 && i % 4 == 0) {
            [result appendString:@"-"];
        }
        [result appendFormat:@"%02x", hashedChars[i]];
    }
    
    return result;
}

@end
